#include "dirclass.h"
#include <cstdio>
#include <algorithm>

bool dir_t::open(char *path){
	strcpy(_dirpath,path);
	return _nowdir=opendir(path);
}

void dir_t::select(char exclist[][NAME_LEN], int exccnt){
	int tmpfcnt=0;
	for(int i=0; i<_files.size(); i++){
		bool exclude=false;
		for(int j=0; j<exccnt; j++){
			if(strcmp(exclist[j],_files[i]->d_name)==0){
				exclude=true;
				break;
			}
		}
		if(!exclude) _files[tmpfcnt++]=_files[i];
	}
	_files.erase(_files.begin()+tmpfcnt,_files.end());
}

void dir_t::scanentries(char exclist[][NAME_LEN], int exccnt){
	if(!_nowdir) return;
	dirent *tmp=NULL;
	while(tmp=readdir(_nowdir)){
		if(tmp->d_type!=DT_REG){
			if(tmp->d_type==DT_DIR) _subdirs.push_back(tmp);
			continue;
		}
		_files.push_back(tmp);
	}
	if(exccnt) this->select(exclist,exccnt);
}

int getprefix(const char *a, const char *b){
	int la=strlen(a), lb=strlen(b);
	for(int i=0; i<min(la,lb); i++)
		if(a[i]!=b[i]) return i;
	return 0;
}

int getsuffix(const char *a, const char *b){
	int la=strlen(a), lb=strlen(b);
	for(int i=la-1,j=lb-1; i>=0 && j>=0; i--,j--)
		if(a[i]!=b[j]) return la-i-1;
	return 0;
}

char* dir_t::findcorr(const char *orifile){
	if(!_nowdir) return NULL;
	int maxprefix=0, maxsuffix=0, maxpos=-1;
	for(int i=0; i<_files.size(); i++){
		int tmp=getprefix(orifile,_files[i]->d_name);
		if(maxprefix<tmp){
			maxprefix=tmp; maxpos=i;
		}
		tmp=getsuffix(orifile,_files[i]->d_name);
		if(maxsuffix<tmp){
			maxsuffix=tmp; maxpos=i;
		}
	}
	return _files[maxpos]->d_name;
}
